import { sys } from 'cc';
import { DEV } from 'cc/env';
import { BattleSystem } from '../battle/BattleSystem';
import { CommandParam, CommandParamMap } from '../battle/Model';
import { CommandType } from '../battle/Enums';
import { EventEmitter } from './event';
import { battleScene } from '../view/scene/BattleSceneManager';
import { LOG } from '../ConsoleLogCtrl';

declare global {
    var gc: GameCore;
}

export class GameCore {
    public event: EventEmitter;
    // 与Django页面通信的桥接对象
    public bridge: any;
    public battle: BattleSystem;
    constructor() {
        this.event = new EventEmitter();
        this.battle = new BattleSystem();
        this.initBattleBridge();
    }

    /**
     * 初始化与Django页面的通信桥接
     */
    private initBattleBridge() {
        // 检查是否在浏览器环境中运行
        if (sys.isBrowser && !DEV) {
            LOG.log('正在初始化战斗桥接...');
            // 注册接收消息的回调（无论battleBridge是否存在都注册）
            window.addEventListener('message', this.onReceiveMessage.bind(this));
            LOG.log('已注册message事件监听器');

            // 获取window对象上的battleBridge
            this.bridge = window?.parent?.['battleBridge'] ?? window?.['battleBridge'];
            if (this.bridge) {
                LOG.log('成功获取battleBridge对象');
            } else {
                LOG.error('无法获取battleBridge对象');
            }
        } else {
            LOG.log('非浏览器环境，跳过通信桥接初始化');
        }
    }
    public notifyParentReady() {
        // 不再向网页发送消息，仅在控制台记录状态
        LOG.log('Cocos已准备就绪');
    }

    /**
     * 接收来自Django页面的消息
     */
    private onReceiveMessage(event: any) {
        const message = event.data;

        // 处理统一消息格式
        if (message.type === 'command' && message.data) {
            LOG.log('收到来自Django页面的CMD消息:', message.data);
            if (message.data.mode == 'replay') {
                if (message.data.rounds && message.data.rounds.length > 0) {
                    // 直接将rounds数据传递给BattleScene进行批量处理
                    const battleSceneInstance = battleScene.getBattleScene();
                    if (battleSceneInstance) {
                        LOG.log('GameCore: 将rounds数据传递给BattleScene进行回放');
                        battleSceneInstance.handleBattleCommandBatch(message.data.rounds as CommandParam<keyof CommandParamMap>[]);
                    } else {
                        LOG.error('GameCore: 无法获取BattleScene实例');
                        this.roundsBattleReplay(message.data.rounds);
                    }
                }
            } else {
                this.battle.cmd(message.data as CommandParam<keyof CommandParamMap>);
            }
        } else {
            LOG.log('收到来自Django页面的消息:', message);
        }
    }

    /**
     * 用battle接口回放rounds数据
     */
    private roundsBattleReplay(rounds: any[]) {
        // 处理第一条命令（init）
        const firstCommand = rounds[0] as CommandParam<keyof CommandParamMap>;
        if (firstCommand.type === CommandType.init) {
            this.battle.cmd(firstCommand);
        }

        // 处理其他命令，按回合分组
        if (rounds.length > 1) {
            const otherCommands = rounds.slice(1);

            // 按回合分组命令
            const roundGroups = new Map<number, CommandParam<keyof CommandParamMap>[]>();
            for (let cmd of otherCommands) {
                const command = cmd as CommandParam<keyof CommandParamMap>;
                const round = command.round || 0;
                if (!roundGroups.has(round)) {
                    roundGroups.set(round, []);
                }
                roundGroups.get(round).push(command);
            }

            const sortedRounds = Array.from(roundGroups.keys()).sort((a, b) => a - b);

            // 使用for循环处理每个回合
            for (const currentRound of sortedRounds) {
                const roundCommands = roundGroups.get(currentRound);

                // 按玩家分组当前回合的命令
                const playerCommands = new Map<string, CommandParam<keyof CommandParamMap>[]>();
                for (let cmd of roundCommands) {
                    const player = cmd.player;
                    if (!playerCommands.has(player)) {
                        playerCommands.set(player, []);
                    }
                    playerCommands.get(player).push(cmd);
                }

                // 为每个玩家提交当前回合的命令
                for (const [player, commands] of playerCommands) {
                    const result = this.battle.submitRoundCommands(player, commands);
                    if (!result.success) {
                        LOG.error(`玩家 ${player} 第${currentRound}回合的命令提交失败:`, result.error);
                    }
                }
            }
        }
    }

    /**
     * 发送消息到Django页面（已禁用）
     */
    public sendToDjango(message) {
        // 不再向网页发送消息
        LOG.log('sendToDjango已禁用，消息:', message);
    }
}

globalThis.gc = new GameCore();
